package com.ibm.spatiotemp.processor;

import org.apache.log4j.Logger;

import com.ibm.spatiotemp.datamodel.datatype.request.QueryRequest;
import com.ibm.spatiotemp.server.config.LocalConfig;
import com.ibm.spatiotemp.source.GPSDataSouceFactory;
import com.ibm.spatiotemp.source.GPSDataSource;

/*
 * class for deduce index building path via data source's meta infos.
 */
public class IndexPathFinder {

	public static Logger logger = Logger.getLogger(IndexPathFinder.class);
	
	/*order for lst layer: datasrcname,"rtree_1st",starttimeidx_endtimeidx*/
//	public static String pathformat_1stidx = LocalConfig.HDFSPrefix+"/%s/rtree_1st/%d/data_00001.rtree";
	/*order for 2nd layer: datasrcname,"rtree_2nd",modid,starttimeidx_endtimeidx,data_00001.rtree*/
//	public static String pathformat_2ndidx = LocalConfig.HDFSPrefix+"/%s/rtree_2nd/%s/%d/data_00001.rtree";
	
	public String[] find1stIndexPath(QueryRequest request){
		String dsrcname = request.getDatasrcid();
		GPSDataSource dsrc  = GPSDataSouceFactory.getGPSDataSource(dsrcname);
		long scale = dsrc.getIndexScale();
		long starts = request.getStartts() < dsrc.getMostEarlyTimeStamp() ? dsrc.getMostEarlyTimeStamp():request.getStartts();
		long endts = request.getEndts();
		
		int scaled_startts = (int)((starts)/scale);
		int scaled_endts = endts%scale!=0? (int)((endts)/scale)+1:(int)((endts)/scale);
		
		int size = scaled_endts - scaled_startts + 1;
		
		String[] result = new String[size];
		
		for (int i = 0; i < size; i++) {
			String resultpath = String.format(LocalConfig.IndexPathFormat1stLayer, dsrcname, (i+scaled_startts)+""); 
			result[i] = resultpath;
		}
		
		return result;
		
	}
	
	public String[] find2ndIndexPath(QueryRequest request)
	{
		String dsrcname = request.getDatasrcid();
		GPSDataSource dsrc  = GPSDataSouceFactory.getGPSDataSource(dsrcname);
		long scale = dsrc.getIndexScale();
		long starts = request.getStartts() < dsrc.getMostEarlyTimeStamp() ? dsrc.getMostEarlyTimeStamp():request.getStartts();
		long endts = request.getEndts();
		
		int scaled_startts = (int)((starts)/scale);
		int scaled_endts = endts%scale!=0? (int)((endts)/scale)+1:(int)((endts)/scale);
		
		int size = scaled_endts - scaled_startts + 1;
		
		String[] result = new String[size];
		String[] modids = request.getModids();
		
		if(modids == null || modids.length > 1)
		{
			logger.error("assert modids.length==1 for 2nd index layer searching");
			return null;
		}
		
		for (int i = 0; i < size; i++) {
			String resultpath = String.format(LocalConfig.IndexPathFormat2ndLayer, dsrcname, modids[0], (i+scaled_startts)+""); 
			result[i] = resultpath;
		}
		
		return result;
	}
	
	
}
